<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品类型管理</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            min-height: 100vh;
            background-color: #f5f5f5;
        }
        .sidebar {
            background-color: #ff5000;
            color: white;
            padding: 15px;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            width: 250px;
            min-height: 100vh;
        }
        .sidebar h1 {
            margin: 0 0 20px 0;
        }
        .menu {
            display: flex;
            flex-direction: column;
            gap: 20px;
            width: 100%;
        }
        .menu a {
            color: white;
            text-decoration: none;
            padding: 10px 15px;
            border-radius: 5px;
            transition: background-color 0.3s;
            width: 100%;
            box-sizing: border-box;
        }
        .menu a:hover {
            background-color: #e04a00;
        }
        .content {
            flex-grow: 1;
            padding: 20px;
            background-color: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            margin: 20px;
            border-radius: 10px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        table, th, td {
            border: 1px solid #ccc;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #f5f5f5;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input, .form-group select, .form-group textarea {
            width: calc(100% - 20px);
            padding: 10px;
            margin-bottom: 5px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        .form-group button {
            padding: 10px 20px;
            background-color: #333;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .form-group button:hover {
            background-color: #555;
        }
        .actions {
            padding: 20px;
            background-color: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            border-radius: 10px;
            margin: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        .actions button {
            padding: 10px 20px;
            background-color: #333;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .actions button:hover {
            background-color: #555;
        }
    </style>
</head>
<body>
<div class="sidebar">
    <h1>商品类型管理</h1>
    <div class="menu">
        <a href="admin">管理员主页</a>
        <a href="adminproduct">商品管理</a>
        <a href="adminorder">订单管理</a>
        <a href="adminusers">用户管理</a>
        <a href="login1">登出</a>
    </div>
</div>

<div class="content">
    <h2>商品类型管理</h2>
    <div class="actions">
        <button onclick="showAddProductType()">新增商品类型</button>
        <button onclick="showProductTypeList()">商品类型列表</button>
    </div>
    <div id="moduleContent"></div>
</div>

<script>
    window.onload = function() {
        showProductTypeList();
    };

    function showAddProductType() {
        fetch('/product-category/parent/0')
            .then(response => response.json())
            .then(data => {
                var options = '<option value="0">无 (顶级类型)</option>';
                data.forEach(type => {
                    if (type.level === 0) {
                        options += `<option value="${type.id}">${type.name}</option>`;
                    }
                });

                document.getElementById('moduleContent').innerHTML = `
                    <h3>新增商品类型</h3>
                    <div class="form-group">
                        <label for="parent-id">父级类型</label>
                        <select id="parent-id" name="parent-id" onchange="handleParentChange()">
                            ${options}
                        </select>
                    </div>
                    <div id="child-select-container" class="form-group" style="display: none;">
                        <label for="child-id">一级类型</label>
                        <select id="child-id" name="child-id">
                            <option value="0">无 (选择一级类型)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="type-name">商品类型名称</label>
                        <input type="text" id="type-name" name="type-name">
                    </div>
                    <div class="form-group">
                        <button onclick="addProductType()">新增商品类型</button>
                    </div>
                `;
            });
    }

    function handleParentChange() {
        var parentId = document.getElementById('parent-id').value;
        var childSelectContainer = document.getElementById('child-select-container');

        // 清除以前的一级类型选择框内容
        childSelectContainer.innerHTML = '';

        if (parentId !== '0') {
            // 请求获取对应顶级类型的一级类型
            fetch(`/product-category/parent/${parentId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.length > 0) {
                        var options = '<option value="0">无 (选择一级类型)</option>';
                        data.forEach(type => {
                            if (type.level === 1) {
                                options += `<option value="${type.id}">${type.name}</option>`;
                            }
                        });

                        // 更新一级类型选择框的内容，并显示
                        childSelectContainer.innerHTML = `
                        <label for="child-id">一级类型</label>
                        <select id="child-id" name="child-id">
                            ${options}
                        </select>
                    `;
                        childSelectContainer.style.display = 'block';
                    } else {
                        // 如果没有一级类型，则直接显示并设置一个默认的选项
                        childSelectContainer.innerHTML = `
                        <label for="child-id">一级类型</label>
                        <select id="child-id" name="child-id">
                            <option value="0">无 (选择一级类型)</option>
                        </select>
                    `;
                        childSelectContainer.style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('Error fetching child types:', error);
                });
        } else {
            // 如果选择了顶级类型 "无 (顶级类型)"，则隐藏一级类型选择框
            childSelectContainer.style.display = 'none';
        }
    }





    function showProductTypeList() {
        fetch('/product-category/parent/0') // 假设0表示顶级商品类型的父ID
            .then(response => response.json())
            .then(data => {
                var content = '<h3>商品类型列表</h3>';
                if (data.length > 0) {
                    content += '<table>';
                    content += '<thead><tr><th>名称</th><th>操作</th></tr></thead>';
                    content += '<tbody>';
                    data.forEach(type => {
                        if (type.level === 0) { // 只显示级别为0的商品类型
                            content += '<tr>';
                            content += `<td>${type.name}</td>`;
                            content += `<td>
                                <button onclick="showSubcategories(${type.id}, ${type.level + 1})">查看子类</button>
                                <button onclick="editProductType(${type.id}, '${type.name}')">修改</button>
                                <button onclick="deleteProductType(${type.id}, '${type.name}')">删除</button>
                            </td>`;
                            content += '</tr>';
                        }
                    });
                    content += '</tbody>';
                    content += '</table>';
                } else {
                    content += '<p>没有找到任何结果</p>';
                }
                document.getElementById('moduleContent').innerHTML = content;
            })
            .catch(error => {
                document.getElementById('moduleContent').innerHTML = `<p>发生错误: ${error.message}</p>`;
            });
    }

    function showSubcategories(parentId, level) {
        fetch('/product-category/' + parentId)
            .then(response => response.json())
            .then(parentCategory => {
                fetch('/product-category/parent/' + parentId)
                    .then(response => response.json())
                    .then(data => {
                        var content = `<h3>子类列表 (上级名称: ${parentCategory.name})</h3>`;
                        if (data.length > 0) {
                            content += '<table>';
                            content += '<thead><tr><th>名称</th><th>操作</th></tr></thead>';
                            content += '<tbody>';
                            data.forEach(type => {
                                if (type.level === level) { // 只显示当前级别的商品类型
                                    content += '<tr>';
                                    content += `<td>${type.name}</td>`;
                                    if (level === 1) {
                                        content += `<td>
                                        <button onclick="showSubcategories(${type.id}, ${type.level + 1})">查看子类</button>
                                        <button onclick="editProductType(${type.id}, '${type.name}')">修改</button>
                                        <button onclick="deleteProductType(${type.id}, '${type.name}')">删除</button>
                                    </td>`;
                                    } else {
                                        content += `<td>
                                        <button onclick="editProductType(${type.id}, '${type.name}')">修改</button>
                                        <button onclick="deleteProductType(${type.id}, '${type.name}')">删除</button>
                                    </td>`;
                                    }
                                    content += '</tr>';
                                }
                            });
                            content += '</tbody>';
                            content += '</table>';
                        } else {
                            content += '<p>没有找到任何结果</p>';
                        }
                        document.getElementById('moduleContent').innerHTML = content;
                    })
                    .catch(error => {
                        document.getElementById('moduleContent').innerHTML = `<p>发生错误: ${error.message}</p>`;
                    });
            })
            .catch(error => {
                document.getElementById('moduleContent').innerHTML = `<p>发生错误: ${error.message}</p>`;
            });
    }

    function addProductType() {
        var parentId = document.getElementById('parent-id').value;
        var childId = document.getElementById('child-id').value;
        var typeName = document.getElementById('type-name').value;

        // 检查第二个下拉菜单是否有选中值，如果有则使用它的值作为parentId
        if (childId !== '0' && childId !== undefined) {
            parentId = childId;
        }

        // 如果parentId为0或者空，则设为null
        if (parentId === '0') {
            parentId = null;
        }

        // 检查是否存在相同名称的商品类型
        fetch('/product-category/check-name', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name: typeName })
        })
            .then(response => response.json())
            .then(data => {
                if (data.exists) {
                    alert('该名称的商品类型已存在');
                } else {
                    // 如果不存在相同名称的商品类型，则继续添加
                    fetch('/product-category/add', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ parentId: parentId, name: typeName })
                    })
                        .then(response => response.json())
                        .then(data => {
                            alert('新增商品类型成功: ' + data.name);
                            showProductTypeList(); // 可以刷新商品类型列表或进行其他操作
                        })
                        .catch(error => {
                            alert('发生错误: ' + error.message);
                        });
                }
            })
            .catch(error => {
                alert('发生错误: ' + error.message);
            });
    }


    function deleteProductType(id, name) {
        // 检查是否有子级类型
        fetch(`/product-category/has-subcategories/${id}`)
            .then(response => response.json())
            .then(data => {
                if (data.hasSubcategories) {
                    alert(`商品类型 "${name}" 有子级类型，请先删除所有子级类型后再试`);
                } else {
                    // 检查是否有商品
                    fetch(`/product-category/has-products/${id}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data.hasProducts) {
                                alert(`商品类型 "${name}" 中有商品，无法删除`);
                            } else {
                                // 确认是否删除
                                if (confirm(`确定要删除商品类型 "${name}" 吗？`)) {
                                    fetch(`/product-category/delete/${id}`, {
                                        method: 'DELETE',
                                    })
                                        .then(response => {
                                            if (response.ok) {
                                                alert(`删除商品类型 "${name}" 成功`);
                                                showProductTypeList(); // 删除成功后刷新列表
                                            } else {
                                                return response.json().then(data => {
                                                    throw new Error(data.message || '删除失败');
                                                });
                                            }
                                        })
                                        .catch(error => {
                                            alert(`删除商品类型 "${name}" 失败: ${error.message}`);
                                        });
                                }
                            }
                        })
                        .catch(error => {
                            alert(`无法确定商品类型 "${name}" 是否有商品: ${error.message}`);
                        });
                }
            })
            .catch(error => {
                alert(`无法确定商品类型 "${name}" 是否有子级类型: ${error.message}`);
            });
    }

    function editProductType(id, name) {
        document.getElementById('moduleContent').innerHTML = `
                <h3>修改商品类型</h3>
                <div class="form-group">
                    <label for="new-type-name">商品类型名称</label>
                    <input type="text" id="new-type-name" name="new-type-name" value="${name}">
                </div>
                <div class="form-group">
                    <button onclick="updateProductType(${id})">保存修改</button>
                </div>
            `;
    }

    function updateProductType(id) {
        var newName = document.getElementById('new-type-name').value;

        fetch('/product-category/update', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `id=${id}&name=${newName}`
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.text(); // 因为我们不期望返回 JSON
            })
            .then(data => {
                alert('修改商品类型成功');
                showProductTypeList();
            })
            .catch(error => {
                alert('发生错误: ' + error.message);
            });
    }


</script>
</body>
</html>
